import React, { useState } from 'react'
import { Layout, Dropdown, Avatar, Button, Modal, Form, Input, message, Typography, Menu } from 'antd'
import { 
  UserOutlined, 
  LogoutOutlined, 
  SettingOutlined
} from '@ant-design/icons'
import { useNavigate, useLocation } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'

const { Header: AntHeader } = Layout
const { Title } = Typography

const Header = () => {
  const { user, logout, updateProfile, changePassword } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()
  
  const [profileModalVisible, setProfileModalVisible] = useState(false)
  const [passwordModalVisible, setPasswordModalVisible] = useState(false)
  const [profileForm] = Form.useForm()
  const [passwordForm] = Form.useForm()
  const [loading, setLoading] = useState(false)

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人信息',
    },
    {
      key: 'password',
      icon: <SettingOutlined />,
      label: '修改密码',
    },
    {
      type: 'divider',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      danger: true,
    },
  ]

  const handleUserMenuClick = async ({ key }) => {
    switch (key) {
      case 'profile':
        setProfileModalVisible(true)
        profileForm.setFieldsValue({
          email: user?.email || ''
        })
        break
      case 'password':
        setPasswordModalVisible(true)
        passwordForm.resetFields()
        break
      case 'logout':
        await logout()
        navigate('/login')
        break
      default:
        break
    }
  }

  const handleProfileUpdate = async (values) => {
    setLoading(true)
    const result = await updateProfile(values)
    setLoading(false)
    
    if (result.success) {
      message.success('个人信息更新成功')
      setProfileModalVisible(false)
    } else {
      message.error(result.message || '更新失败')
    }
  }

  const handlePasswordChange = async (values) => {
    setLoading(true)
    const result = await changePassword(values)
    setLoading(false)
    
    if (result.success) {
      message.success('密码修改成功')
      setPasswordModalVisible(false)
      passwordForm.resetFields()
    } else {
      message.error(result.message || '密码修改失败')
    }
  }

  const userMenu = (
    <Menu items={userMenuItems} onClick={handleUserMenuClick} />
  )

  return (
    <>
      <AntHeader style={{
        background: '#fff',
        padding: '0 24px',
        boxShadow: '0 1px 4px rgba(0,21,41,.08)',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div>
          <Title level={4} style={{ margin: 0 }}>
            Things IoT Platform
          </Title>
        </div>
        
        <Dropdown overlay={userMenu} placement="bottomRight">
          <div style={{
            display: 'flex',
            alignItems: 'center',
            cursor: 'pointer',
            padding: '8px 12px',
            borderRadius: '6px',
            transition: 'background-color 0.3s',
            border: '1px solid #d9d9d9'
          }}>
            <Avatar
              icon={<UserOutlined />}
              style={{ marginRight: 8 }}
            />
            <span>{user?.username}</span>
          </div>
        </Dropdown>
      </AntHeader>

      {/* 个人信息模态框 */}
      <Modal
        title="个人信息"
        open={profileModalVisible}
        onCancel={() => setProfileModalVisible(false)}
        footer={null}
      >
        <Form
          form={profileForm}
          layout="vertical"
          onFinish={handleProfileUpdate}
        >
          <Form.Item
            label="用户名"
          >
            <Input value={user?.username} disabled />
          </Form.Item>
          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱地址' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: 8 }}>
              更新
            </Button>
            <Button onClick={() => setProfileModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改密码模态框 */}
      <Modal
        title="修改密码"
        open={passwordModalVisible}
        onCancel={() => setPasswordModalVisible(false)}
        footer={null}
      >
        <Form
          form={passwordForm}
          layout="vertical"
          onFinish={handlePasswordChange}
        >
          <Form.Item
            name="old_password"
            label="旧密码"
            rules={[{ required: true, message: '请输入旧密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="new_password"
            label="新密码"
            rules={[
              { required: true, message: '请输入新密码' },
              { min: 6, message: '密码长度至少6位' }
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="confirm_password"
            label="确认新密码"
            dependencies={['new_password']}
            rules={[
              { required: true, message: '请确认新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('new_password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading} style={{ marginRight: 8 }}>
              修改密码
            </Button>
            <Button onClick={() => setPasswordModalVisible(false)}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default Header